package com.exam.api.modules.goods.utils.bs;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.exam.api.common.exception.GlobalException;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Log4j2
@Component
public class BSRequest {

    private static final String APP_ID = "yuanxiao";
    private static final String APP_SECRET = "MmYxZGFmMjhjNDQ3ZjYzODcyNGY4MGJi";
    private static final String URL = "https://www.plaso.cn/dataentry";

    public BSResponse removeUserToClass(String userId, Long classId){
        List<String> studentIds = Collections.singletonList(userId);
        Map<String, Object> param = new HashMap<>();
        param.put("groupId", classId);
        param.put("studentIds", JSONUtil.toJsonStr(studentIds));
        param = signature(param);
        String post = HttpUtil.post(URL + "/group/remove", JSONUtil.toJsonStr(param));

        BSResponse response = JSONUtil.toBean(post, BSResponse.class);
        log.info("移除课堂:{}",response);
        return response;
    }

    public BSResponse addUserToClass(String userId,Long classId){
        List<String> studentIds = Collections.singletonList(userId);
        Map<String, Object> param = new HashMap<>();
        param.put("groupId", classId);
        param.put("studentIds", JSONUtil.toJsonStr(studentIds));
        param = signature(param);
        String post = HttpUtil.post(URL + "/group/join", JSONUtil.toJsonStr(param));

        BSResponse response = JSONUtil.toBean(post, BSResponse.class);
        log.info("加入课堂:{}",response);
        return response;
    }

    public List<BSClass> findClassList(){
        List<BSClass> list = new ArrayList<>();
        Integer pageStart = 0;
        Integer pageSize = 50;
        while (true){
            Map<String, Object> param = new HashMap<>();
            param.put("pageStart", pageStart);
            param.put("pageSize", pageSize);
            param = signature(param);
            String post = HttpUtil.post(URL + "/group/list", JSONUtil.toJsonStr(param));

            BSResponse response = JSONUtil.toBean(post, BSResponse.class);
            if(response.getCode() == 0){
                JSONObject obj = response.getObj();
                Integer total = obj.getInt("total");
                list.addAll(obj.getJSONArray("list").toList(BSClass.class));
                if(list.size() >= total){
                    break;
                }
                pageStart += pageSize;
            }else {
                throw new GlobalException(response.getMsg());
            }
        }
        return list;
    }

    public List<BSPackage>  findPackageList(){
        Map<String, Object> param = new HashMap<>();
        param.put("pageStart", 0);
        param.put("pageSize", 999);
        param = signature(param);
        String post = HttpUtil.post(URL + "/package/list", param);

        BSResponse response = JSONUtil.toBean(post, BSResponse.class);
        if(response.getCode() == 0){
            return response.getPackages().toList(BSPackage.class);
        }else {
            throw new GlobalException(response.getMsg());
        }
    }
    public BSUser findUserByPhone(String phone){
        Map<String, Object> param = new HashMap<>();
        param.put("userRole", "student");
        param.put("searchStr", phone);
        param.put("pageStart", 0);
        param.put("pageSize", 50);
        param = signature(param);
        String post = HttpUtil.post(URL + "/user/list", param);

        BSResponse response = JSONUtil.toBean(post, BSResponse.class);
        if(response.getCode() == 0){
            JSONObject obj = response.getObj();
            Integer total = obj.getInt("total");
            if(total == 1){
                //精准找到用户
                List<BSUser> list = obj.getJSONArray("list").toList(BSUser.class);
                return list.get(0);
            } else if(total == 0){
                //没有找到用户，需要添加
                return null;
            }else {
                //找到多个用户，需要异常处理
                throw new GlobalException("找到多个用户");
            }
        }else {
            throw new GlobalException(response.getMsg());
        }
    }

    public BSUser findUserById(BSAddUser addUser){
        Map<String, Object> param = new HashMap<>();
        param.put("userRole", "student");
        param.put("id", addUser.getUserId());
        param.put("loginName", addUser.getLoginFullName());
        param = signature(param);
        String post = HttpUtil.post(URL + "/user/detail", param);

        BSResponse response = JSONUtil.toBean(post, BSResponse.class);
        if(response.getCode() == 0){
            JSONObject obj = response.getObj();
            return JSONUtil.toBean(obj,BSUser.class);
        }else {
            throw new GlobalException(response.getMsg());
        }
    }

    public BSResponse delUser(String userId){
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        param = signature(param);
        String post = HttpUtil.post(URL + "/user/del", param);

        return JSONUtil.toBean(post, BSResponse.class);
    }

    public BSAddUser addUser(String mobile){
        Map<String, Object> param = new HashMap<>();
        param.put("loginName", mobile);
        param.put("password", mobile);
        param.put("userRole", "student");
//        param.put("mobile", mobile);
         param = signature(param);
        String post = HttpUtil.post(URL + "/user/add", param);
        log.info("伯索添加用户{}",post);
        BSResponse response = JSONUtil.toBean(post, BSResponse.class);
        if(response.getCode() == 0){
            return JSONUtil.toBean(response.getObj(), BSAddUser.class);
        }
        if(response.getCode() == 103){
            return JSONUtil.toBean(response.getObj(), BSAddUser.class);
        }
        return null;
    }

    public Map<String, Object> signature( Map<String, Object> param){
        Map<String,Object> p = new HashMap<>(param);
        p.put("appId", APP_ID);
        p.put("validBegin", System.currentTimeMillis() / 1000);
        p.put("validTime", 60);

        TreeMap<String, Object> sortedParams = new TreeMap<>(p);

        String appendString = sortedParams.keySet().stream().map(key -> key + "=" + sortedParams.get(key)).collect(Collectors.joining("&"));
        String signature = new HmacUtils(HmacAlgorithms.HMAC_SHA_1, APP_SECRET)
                .hmacHex(appendString)
                .toUpperCase();
        p.put("signature", signature);
        return p;
    }

}
